﻿using BLL;
using Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace UtilityHelper
{
   public class CameraHelper
    {

        private static volatile CameraHelper instance = null;
        private static object lockHelper = new object();

        private CHCNetSDK.MSGCallBack m_falarmData = null;

        private Dictionary<int, CAMERA_MSG_ENTITY> m_CameraInfoDic;
        private CAMERA_INFO m_UserInfo;
        private Flecks m_fleck;
        public bool InitSDK = false;

        public static CameraHelper GetInstance()
        {
            lock (lockHelper)
            {
                if (instance == null)
                {
                    instance = new CameraHelper();
                    instance.InitSDK = CHCNetSDK.NET_DVR_Init();
                    CAMERA_INFO_BLL bll = new CAMERA_INFO_BLL();
                    instance.m_UserInfo = bll.GetModel(1);
                    instance.m_CameraInfoDic = new Dictionary<int, CAMERA_MSG_ENTITY>();
                }
                instance.m_falarmData = new CHCNetSDK.MSGCallBack(instance.MsgCallback);
                CHCNetSDK.NET_DVR_SetDVRMessageCallBack_V30(instance.m_falarmData, IntPtr.Zero);
                return instance;
            }
        }

        public void MsgCallback(int lCommand, ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            //通过lCommand来判断接收到的报警信息类型，不同的lCommand对应不同的pAlarmInfo内容
            switch (lCommand)
            {
                case CHCNetSDK.COMM_UPLOAD_PLATE_RESULT://交通抓拍结果上传(老报警信息类型)
                    ProcessCommAlarm_Plate(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_ITS_PLATE_RESULT://交通抓拍结果上传(新报警信息类型)
                    ProcessCommAlarm_ITSPlate(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 新报警信息类型
        /// </summary>
        /// <param name="pAlarmer"></param>
        /// <param name="pAlarmInfo"></param>
        /// <param name="dwBufLen"></param>
        /// <param name="pUser"></param>
        private void ProcessCommAlarm_ITSPlate(ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            try
            {
                CHCNetSDK.NET_ITS_PLATE_RESULT struITSPlateResult = new CHCNetSDK.NET_ITS_PLATE_RESULT();
                uint dwSize = (uint)Marshal.SizeOf(struITSPlateResult);

                struITSPlateResult = (CHCNetSDK.NET_ITS_PLATE_RESULT)Marshal.PtrToStructure(pAlarmInfo, typeof(CHCNetSDK.NET_ITS_PLATE_RESULT));

                //报警设备IP地址
                string strIP = pAlarmer.sDeviceIP;

                string lineNum = GetLineNumByIp(strIP);

                string strHPHM = struITSPlateResult.struPlateInfo.sLicense;
                string strHPZL = string.Empty;

                if (string.IsNullOrEmpty(strHPHM) == false)
                {
                    if (strHPHM != "无车牌")
                    {
                        strHPZL = GetHPZL(strHPHM);
                        strHPHM = strHPHM.Substring(1, strHPHM.Length - 1);
                    }
                    else
                    {
                        strHPHM = string.Empty;
                    }
                }
                m_fleck = Flecks.GetInstance();

                //向页面发送消息
                if (m_fleck != null)
                {
                    CONST_DEFINE_WEB_BLL bll = new CONST_DEFINE_WEB_BLL();
                    CONST_DEFINE_WEB entity = bll.GetModel(38);

                    string QY = string.Empty;
                    string HM = string.Empty;
                    if (strHPHM != string.Empty)
                    {
                        QY = strHPHM.Substring(0, 1); //车牌区域代号部分
                        HM = strHPHM.Substring(1);   //车牌号码部分
                    }
                    m_fleck.SendMsg(@"{'Mark':'AJLogin','Msg':[{HM:'" + HM + "',QY:'" + QY + "',IP:'" + strIP + "',ZL:'" + strHPZL + "',LN:'" + lineNum + "',isOnline:'" + entity.Code + "'}]}");
                }
            }
            catch (Exception ex)
            {
                m_fleck.SendMsg(ex.Message);
            }
        }

        /// <summary>
        /// 老报警信息
        /// </summary>
        /// <param name="pAlarmer"></param>
        /// <param name="pAlarmInfo"></param>
        /// <param name="dwBufLen"></param>
        /// <param name="pUser"></param>
        private void ProcessCommAlarm_Plate(ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            CHCNetSDK.NET_ITS_PLATE_RESULT struITSPlateResult = new CHCNetSDK.NET_ITS_PLATE_RESULT();
            uint dwSize = (uint)Marshal.SizeOf(struITSPlateResult);

            struITSPlateResult = (CHCNetSDK.NET_ITS_PLATE_RESULT)Marshal.PtrToStructure(pAlarmInfo, typeof(CHCNetSDK.NET_ITS_PLATE_RESULT));

            //报警设备IP地址
            string strIP = pAlarmer.sDeviceIP;
            string lineNum = GetLineNumByIp(strIP);

            //上传结果
            //string stringAlarm = "抓拍上传，" + "车牌：" + struITSPlateResult.struPlateInfo.sLicense + "，车辆序号：" + struITSPlateResult.struVehicleInfo.dwIndex;

            byte b = struITSPlateResult.struPlateInfo.byColor;
            string strHPHM = struITSPlateResult.struPlateInfo.sLicense;
            string strHPZL = GetHPZL(Convert.ToInt32(b), strHPHM);
        }

        #region 获取数据
        private string GetHPZL(int iType, string strHPHM)
        {
            string strType = "";
            switch (iType)
            {
                case 0://蓝牌
                    strType = "02";//小型汽车
                    break;
                case 1://黄牌
                    if (strHPHM.Contains("学"))
                    {//教练车
                        strType = "16";
                    }
                    else
                    {//大型汽车
                        strType = "01";
                    }
                    break;
                case 2://白牌
                    strType = "23";//警用车辆
                    break;
                case 3://黑牌
                    strType = "03";//外籍使馆车
                    break;
                default:
                    strType = "02";
                    break;
            }

            return strType;
        }

        private string GetHPZL(string strHPHM)
        {
            string zlStr = string.Empty;

            string colorStr = strHPHM.Substring(0, 1);  //截取代表颜色的文字
            switch (colorStr)
            {
                case "蓝":
                    zlStr = "02";
                    break;
                case "黄":
                    if (strHPHM.Contains("学"))
                    {
                        zlStr = "16";
                    }
                    else
                    {
                        zlStr = "01";
                    }
                    break;
                case "白":
                    zlStr = "23";
                    break;
                case "黑":
                    zlStr = "03";
                    break;
                case "绿":
                    zlStr = "52";
                    break;
                default:
                    zlStr = "00";
                    break;
            }


            return zlStr;
        }

        /// <summary>
        /// 获取线号
        /// </summary>
        /// <param name="ipAdress">ipi地址</param>
        /// <returns></returns>
        private string GetLineNumByIp(string ipAdress)
        {
            string lineNum = string.Empty;
            CAMERA_INFO_BLL bll = new CAMERA_INFO_BLL();
            var Infos = bll.GetModelList("IsEnabled='True' and CameraIP='" + ipAdress + "'");
            if (Infos.Length > 0)
            {
                lineNum = Infos[0].LineNum;
            }
            return lineNum == string.Empty ? "1" : lineNum;
        }
        #endregion

        #region 注册摄像头 / 布防

        //注册摄像头
        public void RegisterCamera(int lineNum)
        {
            try
            {
                if (!m_CameraInfoDic.Keys.Contains(lineNum) || m_CameraInfoDic[lineNum].Camera_Register_ID < 0)
                {
                    CAMERA_INFO_BLL bll = new CAMERA_INFO_BLL();
                    var Infos = bll.GetModelList("IsEnabled='True' and LineNum='" + lineNum + "'");

                    CHCNetSDK.NET_DVR_DEVICEINFO_V30 DeviceInfo = new CHCNetSDK.NET_DVR_DEVICEINFO_V30();

                    CAMERA_MSG_ENTITY entity = new CAMERA_MSG_ENTITY();

                    if (Infos.Length > 0)
                    {
                        entity.Camera_Register_ID = CHCNetSDK.NET_DVR_Login_V30(Infos[0].CameraIP, Convert.ToInt32(Infos[0].CameraPort), m_UserInfo.UserName, m_UserInfo.UserPwd, ref DeviceInfo);
                    }

                    if (m_CameraInfoDic.Keys.Contains(lineNum))
                    {
                        m_CameraInfoDic[lineNum].Camera_Register_ID = entity.Camera_Register_ID;
                    }
                    else
                    {
                        m_CameraInfoDic.Add(lineNum, entity);
                    }

                    if (entity.Camera_Register_ID > -1)
                    {
                        m_CameraInfoDic[lineNum].IsRegister = true;
                    }
                    else
                    {
                        m_CameraInfoDic[lineNum].IsRegister = false;
                    }
                }
            }
            catch (Exception ex)
            { 
            }
        }

        //设置布防
        public void SetAlert(int lineNum)
        {
            try
            {
                if (m_CameraInfoDic.Keys.Contains(lineNum) && m_CameraInfoDic[lineNum].Camera_Register_ID > -1 && m_CameraInfoDic[lineNum].Camera_SetAlert_Id < 0)
                {
                    CHCNetSDK.NET_DVR_SETUPALARM_PARAM struAlarmParam = new CHCNetSDK.NET_DVR_SETUPALARM_PARAM();
                    struAlarmParam.dwSize = (uint)Marshal.SizeOf(struAlarmParam);
                    struAlarmParam.byLevel = 1; //0- 一级布防,1- 二级布防
                    struAlarmParam.byAlarmInfoType = 1;//智能交通设备有效，新报警信息类型
                    m_CameraInfoDic[lineNum].Camera_SetAlert_Id = CHCNetSDK.NET_DVR_SetupAlarmChan_V41(m_CameraInfoDic[lineNum].Camera_Register_ID, ref struAlarmParam);
                    if (m_CameraInfoDic[lineNum].Camera_SetAlert_Id < 0)
                    {
                        m_CameraInfoDic[lineNum].IsAlert = false;
                    }
                    else
                    {
                        m_CameraInfoDic[lineNum].IsAlert = true;
                    }

                }
            }
            catch (Exception ex)
            {
 
            }
        }

        //撤销布防
        public void CloseAlert(int lineNum)
        {
            try
            {
                if (m_CameraInfoDic.Keys.Contains(lineNum) && m_CameraInfoDic[lineNum].Camera_SetAlert_Id > -1)
                {
                    bool succ = CHCNetSDK.NET_DVR_CloseAlarmChan_V30(m_CameraInfoDic[lineNum].Camera_SetAlert_Id);
                    if (succ)
                    {
                        m_CameraInfoDic[lineNum].Camera_SetAlert_Id = -1;
                        m_CameraInfoDic[lineNum].IsAlert = false;
                    }

                }
            }
            catch (Exception ex)
            { 
            }
        }

        //注销SDK
        public bool CleanUp()
        {
            bool succ = true;
            try
            {
                int[] keys = m_CameraInfoDic.Keys.ToArray();
                foreach (int i in keys)
                {
                    CloseAlert(i);
                    m_CameraInfoDic[i].IsAlert = false;
                    m_CameraInfoDic[i].Camera_Register_ID = -1;
                    m_CameraInfoDic[i].IsRegister = false;
                }
                if (CHCNetSDK.NET_DVR_Cleanup())
                {
                    InitSDK = false;
                }
            }
            catch (Exception ex)
            {
                succ = false;
            }
            return succ;
        }
        #endregion

        #region 获取注册/布防结果
        public CAMERA_MSG_ENTITY GetCameraEntity(int lineNum)
        {
            CAMERA_MSG_ENTITY entity = new CAMERA_MSG_ENTITY();
            if (m_CameraInfoDic.Keys.Contains(lineNum))
            {
                entity = m_CameraInfoDic[lineNum];
            }
            return entity;
        }

        //是否布防
        public bool GetIsAlert(int lineNum)
        {
            bool succ = false;
            if (m_CameraInfoDic.Keys.Contains(lineNum))
            {
                succ = m_CameraInfoDic[lineNum].IsAlert;
            }
            return succ;
        
        }

        //是否注册
        public bool GetIsRegister(int lineNum)
        {
            bool succ = false;
            if (m_CameraInfoDic.Keys.Contains(lineNum))
            {
                succ = m_CameraInfoDic[lineNum].IsRegister;
            }
            return succ;

        }
        #endregion
    }

    public class CAMERA_MSG_ENTITY
    {

        public CAMERA_MSG_ENTITY()
        {
            Camera_Register_ID = -1;
            IsRegister = false;
            Camera_SetAlert_Id = -1;
            IsAlert = false;
        }

        /// <summary>
        /// 摄像头线号
        /// </summary>
        public int LineNum { get; set; }

        /// <summary>
        /// 摄像头注册ID
        /// </summary>
        public int Camera_Register_ID { get; set; }

        /// <summary>
        /// 摄像头是否注册
        /// </summary>
        public bool IsRegister { get; set; }

        /// <summary>
        /// 摄像头布防ID
        /// </summary>
        public int Camera_SetAlert_Id { get; set; }

        /// <summary>
        /// 摄像头是否布防
        /// </summary>
        public bool IsAlert { get; set; }

    }
}
